//
//  ToolsAuthorization.m
//  FirebaseVIN
//
//  Created by ryp-app01 on 2019/7/19.
//  Copyright © 2019年 深圳前海容易配. All rights reserved.
//

#import "ToolsAuthorization.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/PHPhotoLibrary.h>
#import <Contacts/Contacts.h>
#import <objc/runtime.h>
#import <sys/utsname.h>
#include <sys/mount.h>
static ToolsAuthorization *_authorization = nil;

@interface  ToolsAuthorization ()<UIAlertViewDelegate>

@end


@implementation ToolsAuthorization


- (id)copyWithZone:(NSZone *)zone {
    return [[ToolsAuthorization allocWithZone:zone] init];
}
+ (id)allocWithZone:(NSZone *)zone{
    return [self sharedToolsInstance];
}

+(instancetype)sharedToolsInstance{
    static dispatch_once_t dispatch;
    dispatch_once(&dispatch , ^{
        _authorization = [[super allocWithZone:NULL] init];
    });
    return _authorization;
}


-(void)requestAuthorizationCamera:(ToolsAuthCompletedBlock)completed{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        
        AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusNotDetermined:{
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {//第一次允许的操作
                        completed(true);
                    }else{
                        completed(false);
                        [self getCamera];
                    }
                }];
            }
                
                break;
            case AVAuthorizationStatusRestricted:{//允许权限之后的操作
                completed(true);
            }
                
                break;
            case AVAuthorizationStatusDenied:{//不允许权限之后的操作
                completed(false);
                [self getCamera];
            }
                
                break;
            case AVAuthorizationStatusAuthorized:{//系统受限制之后的操作
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {//第一次允许的操作
                        completed(true);
                    }else{
                        completed(false);
                        [self getCamera];
                    }
                }];
            }
                break;
            default:
                break;
        }
    } else {
        completed(false);
        [self getCamera];
    }
    
}




-(void)requestAuthorizationAlbums:(ToolsAuthCompletedBlock)completed{
    //检查相册权限
    
    PHAuthorizationStatus authorization = [PHPhotoLibrary authorizationStatus];
    if (authorization == PHAuthorizationStatusNotDetermined) {
        if (@available(iOS 14, *)) {
            [PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus status) {
                NSLog(@"iOS 14相册请求权限");
                if(status == PHAuthorizationStatusAuthorized){
                     completed(true);
                }else{
                    completed(false);
                    [self getAlbums];
                }
            }];
        } else {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                NSLog(@"requestAuthorization 相册请求权限");
                if(status == PHAuthorizationStatusAuthorized){
                     completed(true);
                }else{
                    completed(false);
                    [self getAlbums];
                }
            }];
        }
    } else {
        NSLog(@"---已经申请获取权限---");
        completed(true);
    }
}

-(void)getContact:(CompletedBlock)callback{
      
    self.callback = callback;
    [self requestAuthorizationForAddressBook];
}

- (void)requestAuthorizationForAddressBook {
    CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
  
    switch (authorizationStatus) {
        case CNAuthorizationStatusNotDetermined:{  // 用户还未进行选择
            CNContactStore *contactStore = [[CNContactStore alloc] init];
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    [self getAddressBook];
                } else {
                    NSLog(@"授权失败, error=%@", error);
                }
            }];
        }
            break;
        case CNAuthorizationStatusRestricted:
            NSLog(@"用户拒绝");
            break;
        case CNAuthorizationStatusDenied:
            NSLog(@"用户拒绝");
            break;
        case CNAuthorizationStatusAuthorized:
            [self getAddressBook];
            break;
        default:
            break;
    }
}

- (void)getAddressBook {
    CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (authorizationStatus == CNAuthorizationStatusAuthorized) {
        NSLog(@"没有授权...");
    }
    
    NSMutableArray *resultAry=[NSMutableArray array];
    // 获取指定的字段,并不是要获取所有字段，需要指定具体的字段
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
            NSString *givenName = contact.givenName;
            NSString *familyName = contact.familyName;
            NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
            
            NSArray *phoneNumbers = contact.phoneNumbers;
            for (CNLabeledValue *labelValue in phoneNumbers) {
                NSString *label = labelValue.label;
                CNPhoneNumber *phoneNumber = labelValue.value;
                NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue);
                [resultAry addObject:
                 @{ @"name":[NSString stringWithFormat:@"%@%@",familyName,givenName],
                    @"number":phoneNumber.stringValue,
                    @"times":@"0",
                }];
            }
        }];
        self.callback(@{ @"address_book":resultAry});
        });
}
-(void)getDeviceInfo:(CompletedBlock)callback{
    
    NSString *device_model = [self getIphoneType];
    NSString* device_name = [[UIDevice currentDevice] systemName];
    NSString* sdk_version = [[UIDevice currentDevice] systemVersion];

    float totalMemory = [ToolsAuthorization getTotalDiskSize];
    int totalMemory1 = totalMemory/1000000000+1;
    NSString *ram_total_size = [NSString stringWithFormat:@"%d",totalMemory1];
    
    CGFloat ram_usable_size  = [[ToolsAuthorization getTotalDiskSpace] floatValue]/1024/1024/1024;
    
    CGFloat width_pixels  = [[UIScreen mainScreen] bounds].size.width;
    CGFloat height_pixels  = [[UIScreen mainScreen] bounds].size.width;
    NSString *device_uuid = [[NSUUID UUID] UUIDString];
    
    NSDictionary *info = @{
        @"brand":@"Apple",
        @"model":device_model,
        @"device_name":device_name,
        @"sdk_version":sdk_version,
        @"release":@"",
       @"serial_number": @"", //设备序列号
        @"last_boot_time": @"",  //最后一次启动时间
        @"network_operator_name": @"", //运营商名称
       @"width_pixels": @(width_pixels), //屏幕宽度
       @"height_pixels": @(height_pixels), //屏幕高度
        @"ram_total_size": ram_total_size, //总内存大小
        @"ram_usable_size":@(ram_usable_size), //内存可用大小
        @"internal_storage_usable": @"", //可用机身自带存储空间大小
        @"internal_storage_total": @"", //总机身自带存储空间大小
        @"memory_card_size": @"", //外接SD卡或U盘总存储空间大小
        @"memory_card_size_use": @"", //外接SD卡或U盘总存储空间已使用量
        @"is_charging": @"1", //是否正在充电
        @"battery_pct": @"", //电池百分比
        @"latitude": @"", //纬度
        @"longitude": @"", //经度
        @"country_name": @"", //国家
        @"admin_area": @"", //省
        @"locality": @"", //市
        @"sub_admin_area": @"", //区
       @"feature_name":@"", //街道
       @"address": @"", //详细地址
       @"network_type": @"", //网络类型
        @"network_ip": @"", //网络ip
        @"network_mac": @"", //mac地址
        @"device_uuid": device_uuid, //设备UUID
        @"physical_size":@"" //设备物理尺寸
    };
    callback(info);
}

#pragma mark -获取设备的内存
+(long long)getTotalDiskSize
{
    struct statfs buf;
    unsigned long long freeSpace = 0;
    if (statfs("/", &buf) >= 0)
    {
        freeSpace = (unsigned long long)(buf.f_bsize * buf.f_blocks);
    }
    return freeSpace;
}
// iOS11 之后使用该方法获取剩余容量
+ (NSString*)getTotalDiskSpace{
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()];
    NSDictionary *results = [fileURL resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:nil];
    NSLog(@"剩余可用空间:%@",results[NSURLVolumeAvailableCapacityForImportantUsageKey]);
    return results[NSURLVolumeAvailableCapacityForImportantUsageKey];
}
#pragma mark -获取设备型号
-(NSString*)getIphoneType{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    if([platform isEqualToString:@"iPhone1,1"])  return @"iPhone 2G";
    if([platform isEqualToString:@"iPhone1,2"])  return @"iPhone 3G";
    if([platform isEqualToString:@"iPhone2,1"])  return @"iPhone 3GS";
    if([platform isEqualToString:@"iPhone3,1"])  return @"iPhone 4";
    if([platform isEqualToString:@"iPhone3,2"])  return @"iPhone 4";
    if([platform isEqualToString:@"iPhone3,3"])  return @"iPhone 4";
    if([platform isEqualToString:@"iPhone4,1"])  return @"iPhone 4S";
    if([platform isEqualToString:@"iPhone5,1"])  return @"iPhone 5";
    if([platform isEqualToString:@"iPhone5,2"])  return @"iPhone 5";
    if([platform isEqualToString:@"iPhone5,3"])  return @"iPhone 5c";
    if([platform isEqualToString:@"iPhone5,4"])  return @"iPhone 5c";
    if([platform isEqualToString:@"iPhone6,1"])  return @"iPhone 5s";
    if([platform isEqualToString:@"iPhone6,2"])  return @"iPhone 5s";
    if([platform isEqualToString:@"iPhone7,1"])  return @"iPhone 6 Plus";
    if([platform isEqualToString:@"iPhone7,2"])  return @"iPhone 6";
    if([platform isEqualToString:@"iPhone8,1"])  return @"iPhone 6s";
    if([platform isEqualToString:@"iPhone8,2"])  return @"iPhone 6s Plus";
    if([platform isEqualToString:@"iPhone8,4"])  return @"iPhone SE";
    if([platform isEqualToString:@"iPhone9,1"])  return @"iPhone 7";
    if([platform isEqualToString:@"iPhone9,3"])  return @"iPhone 7";
    if([platform isEqualToString:@"iPhone9,2"])  return @"iPhone 7 Plus";
    if([platform isEqualToString:@"iPhone9,4"])  return @"iPhone 7 Plus";
    if([platform isEqualToString:@"iPhone10,1"]) return @"iPhone 8";
    if([platform isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    if([platform isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
    if([platform isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    if([platform isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    if([platform isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    if([platform isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    if([platform isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
    if([platform isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
    if([platform isEqualToString:@"iPhone11,4"]) return @"iPhone XS Max";
    return platform;
}
#pragma mark ––––––––––––– 获取手机上所有的应用

-(void)getAppInfoList:(CompletedBlock)callback{
    Class LSApplicationWorkspace = objc_getClass("LSApplicationWorkspace");
    Class LSApplicationProxy = objc_getClass("LSApplicationProxy");

    id defaultWorkspace = [LSApplicationWorkspace performSelector:@selector(defaultWorkspace)];
  
    // 此方法在iOS12+获取不到
//    id allApplications = [defaultWorkspace performSelector:@selector(allInstalledApplications)];
    NSArray *plugins = [defaultWorkspace performSelector:@selector(installedPlugins)];
    
    NSMutableSet *list = [[NSMutableSet alloc] init];
    for (id plugin in plugins) {
        id bundle = [plugin performSelector:@selector(containingBundle)];
        if (bundle) {
            [list addObject:bundle];
        }
    }

    NSMutableArray *_arr = [NSMutableArray arrayWithCapacity:0];
    // 遍历所有app信息
    for (id plugin in list) {
        // BundleID
        NSString *bundleIdentifier = [plugin performSelector:@selector(bundleIdentifier)];
             if (![bundleIdentifier containsString:@"com.apple"]) {
                 NSLog(@"bundleIdentifier -> %@", bundleIdentifier);
            
              NSString *app_package_name = @"";
                 if ([plugin respondsToSelector:@selector(applicationIdentifier)]) {
                     app_package_name = [plugin performSelector:@selector(applicationIdentifier)];
                 }
        
            NSString *installation_time = @"";
            if ([plugin respondsToSelector:@selector(registeredDate)]) {
                NSString* timeString = [plugin performSelector:@selector(registeredDate)];
                NSString *dateString  = timeString.description;
                if(dateString){
//                    NSLog(@"dateString--------%@",dateString);
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZZ"];
                    NSDate *date = [dateFormatter dateFromString:dateString];
                    if (date) {
                        NSTimeInterval timeInterval = [date timeIntervalSince1970] * 1000;
//                        NSLog(@"毫秒时间戳: %.0f", timeInterval);
                        NSString *intervalString = [NSString stringWithFormat:@"%.f", timeInterval];
                        installation_time = intervalString;
//                        NSLog(@"转换字符串毫秒时间戳: %@", intervalString);
                    } else {
                        NSLog(@"日期格式不匹配");
                    }
                }
            }
            
            NSString *app_name = @"";
            if ([plugin respondsToSelector:@selector(itemName)]) {
                app_name = [plugin performSelector:@selector(itemName)];
            }
            
            NSString * version_number  = @"";
            if ([plugin respondsToSelector:@selector(shortVersionString)]) {
                version_number = [plugin performSelector:@selector(shortVersionString)];
            }
         
         /**
          NSString *applicationDSID = [plugin performSelector:@selector(applicationDSID)];
          NSLog(@"applicationDSID -> %@", applicationDSID);
          NSString *applicationIdentifier = [plugin performSelector:@selector(applicationIdentifier)];
          NSLog(@"applicationIdentifier -> %@", applicationIdentifier);
          NSString *applicationType = [plugin performSelector:@selector(applicationType)];
          NSLog(@"applicationType -> %@", applicationType);
          NSString *dynamicDiskUsage = [plugin performSelector:@selector(dynamicDiskUsage)];
          NSLog(@"dynamicDiskUsage -> %@", dynamicDiskUsage);
          NSString *itemID = [plugin performSelector:@selector(itemID)];
          NSLog(@"itemID -> %@", itemID);
          NSString *itemName = [plugin performSelector:@selector(itemName)];
          NSLog(@"itemName -> %@", itemName);
          NSString *minimumSystemVersion = [plugin performSelector:@selector(minimumSystemVersion)];
          NSLog(@"minimumSystemVersion -> %@", minimumSystemVersion);
          NSString *requiredDeviceCapabilities = [plugin performSelector:@selector(requiredDeviceCapabilities)];
          NSLog(@"requiredDeviceCapabilities -> %@", requiredDeviceCapabilities);
          NSString *sdkVersion = [plugin performSelector:@selector(sdkVersion)];
          NSLog(@"sdkVersion -> %@", sdkVersion);
          NSString *shortVersionString = [plugin performSelector:@selector(shortVersionString)];
          NSLog(@"shortVersionString -> %@", shortVersionString);
          NSString *sourceAppIdentifier = [plugin performSelector:@selector(sourceAppIdentifier)];
          NSLog(@"sourceAppIdentifier -> %@", sourceAppIdentifier);
          NSString *staticDiskUsage = [plugin performSelector:@selector(staticDiskUsage)];
          NSLog(@"staticDiskUsage -> %@", staticDiskUsage);
          NSString *teamID = [plugin performSelector:@selector(teamID)];
          NSLog(@"teamID -> %@", teamID);
          NSString *vendorName = [plugin performSelector:@selector(vendorName)];
          NSLog(@"vendorName -> %@", vendorName);
          */
            
            NSDictionary *info = @{
                                   @"installation_time":installation_time.description,
                                   @"is_system_applications":@0,
                                   @"app_package_name":app_package_name.description,
                                   @"version_number":version_number.description,
                                   @"last_update_time":installation_time.description,
                                   @"app_name":app_name.description,
                                   @"version_name":@""
            };
            [_arr addObject:info];
        }
    }
    callback(_arr);
}

// 字符串转时间戳 如：2017-4-10 17:15:10 （精确到毫秒*1000）
+ (NSString *)getTimeStrWithString:(NSString *)str {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}

/// iOS10 -12，判断是否安装app
- (BOOL)isAppInstalled:(NSString *)bundleId {
    NSBundle *container = [NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/MobileContainerManager.framework"];
    if ([container load]) {
        Class appContainer = NSClassFromString(@"MCMAppContainer");
        id install = [appContainer performSelector:@selector(containerWithIdentifier:error:) withObject:bundleId];
        if (install) {
            return YES;
        }
    }
    return NO;
}

/// iOS10-
- (void)getAppInfoList10 {
    Class LSApplicationWorkspace = objc_getClass("LSApplicationWorkspace");
    NSObject* workspace = [LSApplicationWorkspace performSelector:@selector(defaultWorkspace)];
    NSArray *allApplications = [workspace performSelector:@selector(allApplications)];

    Class LSApplicationProxy = object_getClass(@"LSApplicationProxy");
    for (LSApplicationProxy in allApplications) {
        // 查看一些信息
        NSString *bundleID = [LSApplicationProxy performSelector:@selector(applicationIdentifier)];
        NSString *version =  [LSApplicationProxy performSelector:@selector(bundleVersion)];
        NSString *shortVersionString =  [LSApplicationProxy performSelector:@selector(shortVersionString)];
        NSLog(@"bundleID -> %@", bundleID);
    }
}
- (void)getCamera{
    dispatch_async(dispatch_get_main_queue(), ^{
        //判断是否已授权
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相机" message:@"请在iPhone的""设置-APP-相机""中允许使用相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    });
}


- (void)getAlbums{
    dispatch_async(dispatch_get_main_queue(), ^{
        //判断是否已授权
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-APP-照片""中允许访问照片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    });
}


//跳转系统设置,调试使用
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if( [[UIApplication sharedApplication]canOpenURL:settingsURL ]&&settingsURL ) {
        [[UIApplication sharedApplication] openURL:settingsURL];
    }
}


@end
